<template>
  <el-form ref="formRef" :model="form" :rules="rules" label-position="top" @submit.prevent>
    <el-form-item v-for="item in fieldList" :key="item.field" :label="item.name" :prop="item.field" :class="item.type">
      <InitForm :form="form" :data="item" @onSearchFun="handleSearch" />
    </el-form-item>
  </el-form>
</template>
<script lang="tsx">
import InitForm from './init-form'
import { baseForm } from '@/common/mixins/index'
import { getCurrentInstance, computed } from 'vue'
import { formRollToFirstError } from '@/common/utils/common'
import { validPairs } from '@app/customer/mixins/index'
import { commonStore } from '@/common/store/modules/common'
import { deepClone } from '@/common/utils/common'
export default {
  name: 'BaseForm',
  components: { InitForm },
  props: {
    fieldList: {
      // 自定义表单的列表
      type: Array,
      default: () => []
    },
    form: {
      // 自定义表单绑定的form
      type: Object,
      default: () => ({})
    },
    rules: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['onSearchFun'],
  setup(props: any, { emit }: any) {
    const instance: any = getCurrentInstance()

    const globalFieldsObj: any = computed(() => {
      // 获取全局字段obj
      return commonStore().publicCache.globalFieldCacheObj || {}
    })

    const handleSearch = () => {
      baseForm.searchFun(emit)
    }

    const checkForm = async () => {
      // 表单校验
      let status = false
      const saveForm = deepClone(props.form)
      await instance?.refs.formRef.validate((valid: boolean) => {
        if (valid) {
          if (!validPairs(saveForm, globalFieldsObj.value)) {
            return
          }
          status = valid
        } else {
          // 滚动到错误节点
          formRollToFirstError(instance?.refs.formRef.$parent.$parent.$el.parentElement)
        }
      })
      return {
        status,
        form: saveForm
      }
    }

    return { handleSearch, checkForm }
  }
}
</script>
<style lang="stylus" scoped>
.el-form
  display flex
  align-items center
  flex-wrap wrap
  .el-form-item
    margin-right 16px
</style>
